import usersListPageTpl from '../views/users-page.art';
import page from '../databus/page';

//设置页码高亮
const _setCurPageActive = (index) => {
  $('#users-page #users-page-list li:not(:first-child,:last-child)')
    .eq(index - 1)
    .addClass('active')
    .siblings()
    .removeClass('active');
}

//分页功能
const papination = (data, pageSize, currentPage) => {
  //总条数
  const total = data.length;
  const pageCount = Math.ceil(total / pageSize);
  const pageArray = new Array(pageCount);
  //渲染分页模板并传入数据
  const htmlPage = usersListPageTpl({
    pageArray
  });
  $('#users-page').html(htmlPage);

  _setCurPageActive(page.currentPage);

  _bindEvent(data, pageSize);
}

const _bindEvent = (data, pageSize) => {
  //分页事件绑定
  $('#users-page').off('click').on('click', '#users-page-list li:not(:first-child,:last-child)', function () {

    const index = $(this).index();

    page.setCurrentPage(index);

    //抛发事件 发布
    $('body').trigger('changeCurrentPage', index);

    page.setCurrentPage(index);


    _setCurPageActive(index);

  })
  //上一页
  $('#users-page').on('click', '#users-page-list li:first-child', function () {
    if (page.currentPage > 1) {
      page.setCurrentPage(page.currentPage - 1);
      $('body').trigger('changeCurrentPage', page.currentPage);
      _setCurPageActive(page.currentPage);
    }
  })
  //下一页
  $('#users-page').on('click', '#users-page-list li:last-child', function () {
    if (page.currentPage < Math.ceil(data.length / pageSize)) {
      page.setCurrentPage(page.currentPage + 1);
      $('body').trigger('changeCurrentPage', page.currentPage);
      _setCurPageActive(page.currentPage);
    }
  });
}

export default papination